// Cloudflare Worker 入口文件
// 支持静态文件服务和游戏页面路由

// MIME 类型映射
const mimeTypes = {
  '.html': 'text/html',
  '.js': 'text/javascript',
  '.css': 'text/css',
  '.json': 'application/json',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.gif': 'image/gif',
  '.svg': 'image/svg+xml',
  '.wav': 'audio/wav',
  '.mp4': 'video/mp4',
  '.woff': 'application/font-woff',
  '.woff2': 'application/font-woff2',
  '.ttf': 'application/font-ttf',
  '.eot': 'application/vnd.ms-fontobject',
  '.otf': 'application/font-otf',
  '.ico': 'image/x-icon'
};

// 获取文件扩展名
function getExtension(path) {
  const lastDot = path.lastIndexOf('.');
  return lastDot === -1 ? '' : path.slice(lastDot).toLowerCase();
}

// 获取 MIME 类型
function getMimeType(path) {
  const ext = getExtension(path);
  return mimeTypes[ext] || 'application/octet-stream';
}

// 静态文件内容映射 - 这些将在构建时被替换
const staticFiles = {
  '/': `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gemini Game Hall</title>
    <link rel="stylesheet" href="home_style.css">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
</head>
<body>
    <header>
        <h1>Welcome to Gemini Game Hall! ✨🎮</h1>
        <p>Your one-stop destination for exciting browser games.</p>
    </header>

    <main>
        <section class="game-category">
            <h2>Classic Arcade 🕹️</h2>
            <div class="game-list">
                <div class="game-card">
                    <h3>Snake Game 🐍</h3>
                    <p>Navigate your snake, eat food, and grow longer!.</p>
                    <a href="snake_game/index.html" class="play-button">Play Now ▶️</a>
                </div>
                <div class="game-card">
                    <h3>Big Fish Eat Small Fish 🐠</h3>
                    <p>Grow your fish by eating smaller fish, but watch out for bigger ones!</p>
                    <a href="fish_game/index.html" class="play-button">Play Now ▶️</a>
                </div>
                <!-- More games can be added here -->
            </div>
        </section>

        <section class="game-category">
            <h2>Puzzle Fun 🧩</h2>
            <div class="game-list">
                <div class="game-card coming-soon">
                    <h3>Coming Soon! 🚀</h3>
                    <p>Stay tuned for more exciting puzzle games.</p>
                </div>
            </div>
        </section>
    </main>

    <footer>
        <p>© 2025 Gemini Game Hall. All rights reserved. 🌟</p>
    </footer>

    <script src="home_script.js"></script>
</body>
</html>`,

  '/404': `<h1>404 Not Found</h1><p>The requested page could not be found.</p>`
};

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    let pathname = url.pathname;

    // 处理根路径
    if (pathname === '/') {
      return new Response(staticFiles['/'], {
        headers: { 'Content-Type': 'text/html; charset=UTF-8' }
      });
    }

    // 尝试获取静态资源
    try {
      // 首先尝试从 Assets 获取文件
      if (env.ASSETS) {
        const asset = await env.ASSETS.fetch(request);
        if (asset.status !== 404) {
          return asset;
        }
      }

      // 如果 Assets 不可用，尝试从内置的静态文件映射获取
      if (staticFiles[pathname]) {
        const mimeType = getMimeType(pathname);
        return new Response(staticFiles[pathname], {
          headers: { 'Content-Type': mimeType }
        });
      }

      // 处理游戏路径
      if (pathname.startsWith('/snake_game/') || pathname.startsWith('/fish_game/')) {
        // 这里可以根据需要返回相应的游戏文件
        // 暂时返回一个基本的游戏页面框架
        const gameName = pathname.startsWith('/snake_game/') ? 'Snake Game' : 'Fish Game';
        const gameHtml = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${gameName}</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; margin: 50px; }
        .game-container { border: 2px solid #333; margin: 20px auto; }
        .back-link { display: inline-block; margin: 20px; padding: 10px 20px; background: #007bff; color: white; text-decoration: none; border-radius: 5px; }
    </style>
</head>
<body>
    <h1>${gameName}</h1>
    <div class="game-container">
        <p>Game will be loaded here...</p>
    </div>
    <a href="/" class="back-link">← Back to Game Hall</a>
</body>
</html>`;

        return new Response(gameHtml, {
          headers: { 'Content-Type': 'text/html; charset=UTF-8' }
        });
      }

      // 返回 404
      return new Response(staticFiles['/404'], {
        status: 404,
        headers: { 'Content-Type': 'text/html; charset=UTF-8' }
      });

    } catch (error) {
      console.error('Error serving static file:', error);
      return new Response('Internal Server Error', {
        status: 500,
        headers: { 'Content-Type': 'text/plain' }
      });
    }
  }
};